// void, Obj This
Building this;
ObjList ol, list;
Unit u, up;
point pt;
int i, j, percent_health, time, random, random2;
str names, classes;

Sleep(10880+rand(GetConst("RandTimeStart"))+GetConst("AddTimeStart"));

this = This.AsBuilding;
//Sleep(880); 
if (!.IsValid()) return;  

names = "/1/Mine/"+.name;

if(.player == 15){
	random = rand(20)+20;
	random2 = rand(4);
	for(i=0; i<random; i+=1){
		Sleep(rand(100)+100);
	    up = Place("CVillager", .pos, 16); 
        if(up.IsValid)
	        .settlement.ForceAddUnit(up);
                        
        Sleep(rand(50)+10);
	}
	//classes = "CMaceman";
	if(random2 == 0) classes = "CMaceman";
	else if(random2 == 1) classes = "GAxeman";
	else if(random2 == 2) classes = "BShieldBearer";
	else if(random2 == 3) classes = "EHorusWarrior";
	
	for(i=0; i<20; i+=1){
		Sleep(rand(100)+100);
		up = Place(classes, .pos, 15); 
		if(up.IsValid){
			.settlement.ForceAddUnit(up);
			up.SetLevel(1);
			up.SetFeeding( false );
			up.SetEntering( false );
		}		
		Sleep(rand(50)+10);
	}
}
while(.IsValid){ 
	//pr(.player);
	j = 0;
	ol = .settlement.Units;
	ol.ClearDead();
	for (i=0; i<ol.count; i+=1){
        
		u = ol[i].AsUnit;
        if(u.IsValid){
        	if(u.IsHeirOf("Peasant")){
	            percent_health = u.health*100/u.maxhealth;
	            if(percent_health > 30){
                    j+=1;
	            }
	        }
        }
    }
	//pr("Miner: "+j);
	time = 800000 / j;
	if(time > 60000)
		time = 60000;                

	if(j > 0){ 
		EnvWriteInt(.player, "resources/Iron", 1 + EnvReadInt(.player, "resources/Iron"));
		EnvWriteInt(names, time/1000);
	} else { 
		EnvWriteInt(names, 9999);
		time = 5000;
    }
        
	pt = Point(.radius + 25, 0);
	pt.Rot(rand(360));
	pt = pt + .pos;
	list = .settlement().Units().ObjEnemy(.player);
	list.ClearDead();
	list.SetCommand("advance", pt);
        
    Sleep(time);     
}

Sleep(20000);
